package com.iot08.api.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.common.entity.app.DevHCYAuth;
import com.iot08.common.entity.app.Device;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.HttpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 12/16/22 6:37 PM
 */
@Slf4j
@Service
public class DevHCYAuthService extends BaseService<DevHCYAuth> {

    public String HCY_IOS_CHANNELID = "10004";
    public String HCY_Android_CHANNELID = "10003";
    public String HCY_Web_CHANNELID = "10002";
    public String HCY_Hardware_CHANNELID = "10012";

    //默认提前一天检查
    @Value("${hcy.checkTokenExpiryTime:86400}")
    public Integer checkTokenExpiryTime;


    /**
     * 和彩云 的配置列表
     */
    @Value("${hcy.configList:[]}")
    public String HCY_ConfigArrStr;
    public JSONArray HCY_ConfigArr;

    @Value("${hcy.h5platformChannelID:10246500}")
    public String h5platformChannelID;

    //1.2.3刷新Token oauth2/refreshToken
    public String HCYRefreshTokenURL = "https://miniapp.yun.139.com/open-mpplatform/oauth2/refreshToken";

    //1.4.1中间页接入方式获取用户凭证oauth2/accessToken1
    public String HCYMiddlePageGetTokenURL = "https://miniapp.yun.139.com/open-mpplatform/oauth2/accessToken1";

    //授权中间页地址
    public String HCYMiddlePageURL = "https://miniapp.yun.139.com/middle/index.html#/middlePage";

    // 后台代替设备访问授权页后的 请求验证码接口:
    public String HCYGetVcodeURL = "https://miniapp.yun.139.com/open-mpplatform/oauth2/getDyncPasswd1";

    // 后台代替设备请求验证码后, 提交验证码接口:
    public String HCYPostVcodeURL = "https://miniapp.yun.139.com/open-mpplatform/oauth2/verifyDyncPasswd1";

    // 检查当前用户是否在 家庭云内
    public String HCYChectCloudPhoto = "https://miniapp.yun.139.com/richlifeApp/devapp/andAlbum/openApi/queryCloudPhoto";

    // 当前设备邀请 家长加入家庭云
    public String HCYInviteFamilyMember = "https://miniapp.yun.139.com/richlifeApp/devapp/andAlbum/openApi/inviteFamilyMember";

    // 家长确认 加入家庭云
    public String HCYConfirmInvitation = "https://miniapp.yun.139.com/richlifeApp/devapp/andAlbum/openApi/confirmInvitation";

    // 后台单点登录后能得到 授权的登录
    public String HCYSignOnAuthURL = "https://miniapp.yun.139.com/richlifeApp/login/thirdSingleLoginToHCYweb";


//    //保留登录功能的测试环境
//    public String HCYAlbum_H5URL = "https://miniprogram.mail.10086.cn/viewtest/{albumName}test/#/main?albumList={familyId},{albumId}&source={source}";

    //    正式环境的 和彩云H5 功能
    public String HCYAlbum_H5URL = "https://yun.139.com/{albumName}/#/main?albumList={familyId},{albumId}&source={source}&channel={channel}";

    public String HCYAuthBackTemp_H5URL = "https://api.tx.kidxin.com/getway/hcy/hcyTempPage";

    public String HCYDevChannelId = "10003";

    @Resource
    private DeviceService deviceService;

    @Resource
    private KafkaService kafkaService;


    public JSONArray getHCY_ConfigArr() {
        if(HCY_ConfigArr == null){
            HCY_ConfigArr = JSONArray.parseArray(HCY_ConfigArrStr);
        }
        return HCY_ConfigArr;
    }

    public String getAppID(DevHCYAuth devHCYAuth) {
        JSONObject item = this.getHCY_ConfigArr().getJSONObject(devHCYAuth.getProject_type());
        return item.getString("appId");
    }

    public String getAppKey(DevHCYAuth devHCYAuth) {
        JSONObject item = this.getHCY_ConfigArr().getJSONObject(devHCYAuth.getProject_type());
        return item.getString("appKey");
    }

    public String getAppSecret(DevHCYAuth devHCYAuth) {
        JSONObject item = this.getHCY_ConfigArr().getJSONObject(devHCYAuth.getProject_type());
        return item.getString("appSecret");
    }

    public String getAppTitle(DevHCYAuth devHCYAuth) {
        JSONObject item = this.getHCY_ConfigArr().getJSONObject(devHCYAuth.getProject_type());
        return item.getString("ident");
    }

    /**
     * 设备 和彩云相册token 有效期内刷新Token
     *
     * @param device
     * @param devHCYAuth
     * @time: 1/6/23 10:22 AM
     * @author: Weichao
     * @version 1.0
     */
    public JSONObject devHCYRefreshToken(Device device, DevHCYAuth devHCYAuth) {
        JSONObject resultOB = new JSONObject();

        //更新token: 检查token时间
        String dev_accesstoken = devHCYAuth.getDev_accesstoken();
        Long dev_accesstoken_expiry = devHCYAuth.getDev_accesstoken_expiry();
        if (dev_accesstoken == null) {
            //还没有token的
            return null;
        }
        Long nowTime = DateUtil.nowTimestampToLong();
        if ((dev_accesstoken_expiry - nowTime) < this.checkTokenExpiryTime) {
            //还在token有效期内, 只需更新即可.

            //刷新token的参数
            JSONObject refreshTokenParam = new JSONObject();
            refreshTokenParam.put("appId", this.getAppID(devHCYAuth));
            refreshTokenParam.put("appSecret", this.getAppSecret(devHCYAuth));
            refreshTokenParam.put("refreshToken", dev_accesstoken);
            String refreshTokenRes = HttpReq.sendPostJson(this.HCYRefreshTokenURL, refreshTokenParam.toJSONString());
            JSONObject refreshTokenResOB = JSONObject.parseObject(refreshTokenRes);
            if (refreshTokenResOB.getInteger("code") == 0) {
                log.info("imei:{} 更新和彩云相册 token成功 refreshTokenParam:{}  refreshTokenRes:{}", device.getId(), refreshTokenParam, refreshTokenRes);
                /*
                {
                    "code": 0,
                    "message": "成功",
                    "data": {
                        "accessToken": "123",
                        "expiresIn": 168
                    }
                }
                */
                JSONObject data = refreshTokenResOB.getJSONObject("data");
                String newToken = data.getString("accessToken");
                Long newTokenExpiresIn = nowTime + data.getInteger("expiresIn") * 3600;
                devHCYAuth.setDev_accesstoken(newToken);
                devHCYAuth.setDev_accesstoken_expiry(newTokenExpiresIn);
                devHCYAuth.setDev_accesstoken_update(new Date());
                devHCYAuth.setUpdateDate(new Date());
                this.save(devHCYAuth);
                resultOB.put("accesstoken", newToken);
                resultOB.put("expiresTime", newTokenExpiresIn);
                return resultOB;
            } else {
                //更新token失败 走授权的情况
                log.error("imei:{} 更新和彩云相册 token失败(授权有效期内) 走授权的情况 :{}", device.getId(), refreshTokenRes);
                return null;
            }
        } else {
            //暂时不用更新
            log.info("imei:{} 设备 和彩云相册token暂时不用刷新, 有效期至:{}", device.getId(), devHCYAuth.getDev_accesstoken_expiry());
            resultOB.put("accesstoken", dev_accesstoken);
            resultOB.put("expiresTime", dev_accesstoken_expiry);
            return resultOB;
        }

    }

    public boolean checkPhone(String phone) {
        if (phone == null) {
            return false;
        }
        String regex = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(phone);
        return m.matches();
    }
}
